package com.li.sort;

import org.omg.CORBA.PUBLIC_MEMBER;

import java.util.Arrays;

public class MergetSort {
    public static void main(String[] args) {
        int arr[] = {8, 4, 5, 7, 1, 3, 6, 2};
        int temp[] = new int[arr.length];
        mergesort(arr, 0, arr.length - 1, temp);
        System.out.println(Arrays.toString(arr));

    }

    public static void mergesort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            mergesort(arr, left, mid, temp);
            mergesort(arr, mid + 1, right, temp);
            mergr(arr, left, mid, right, temp);
        }

    }

    public static void mergr(int[] arr, int left, int mid, int right, int[] temp) {
        int i = left;//左边有序化初始索引
        int j = mid + 1;//右边有序化初始索引
        int t = 0;//指向temp数组的当前索引
        //先把左右两边的数据按规则填充到temp数组
        //直到有一边处理完
        while (i <= mid && j <= right) {
            if (arr[i] <= arr[j]) {
                temp[t] = arr[i];
                t = t + 1;
                i = i + 1;
            } else {
                temp[t] = arr[j];
                t += 1;
                j += 1;
            }
        }
        //把有剩余的一边数据依次全部填充到temp
        while (i <= mid) {
            temp[t] = arr[i];
            t = t + 1;
            i = i + 1;
        }
        while (j <= right) {
            temp[t] = arr[j];
            t = t + 1;
            j = j + 1;
        }
        //temp拷贝到arr
        t = 0;
        int templeft = left;
        while (templeft <= right) {
            arr[templeft] = temp[t];
            t = t + 1;
            templeft += 1;
        }

    }
}
